import React, { memo, useEffect, useRef, useCallback, useState } from 'react';
import { useSelector, useDispatch, shallowEqual } from 'react-redux';
import { Carousel } from 'antd';

import { getTopBannerAction } from '../../store/actionCreators'
import {
    BannerWrapper,
    BannerLeft,
    BannerRight,
    BannerControl
} from './style';

export default memo(function LwtTopBanner() {
    // state
    const [currentIndex, setCurrentIndex] = useState(0);
    // 组件和redux关联: 获取数据和进行操作
    const { topBanners } = useSelector(state => ({
        topBanners: state.getIn(["recommend", "topBanners"])
    }), shallowEqual);
    const dispatch = useDispatch();
    // 其他hooks
    const bannerRef = useRef();
    useEffect(() => {
        dispatch(getTopBannerAction());
    }, [dispatch]);

    const bannerChange = useCallback((from, to) => {
        setTimeout(() => {
            setCurrentIndex(to);
        }, 0);
    }, []);

    const bgImage = topBanners[currentIndex] && (topBanners[currentIndex].imageUrl + "?imageView&blur=40x20")

    return (
        <BannerWrapper bgImage={bgImage}>
            <div className="banner wrap-v2">
                <BannerLeft>
                    <Carousel effect="fade" autoplay ref={bannerRef} beforeChange={bannerChange}>
                        {
                            topBanners.map((item, index) => {
                                return (
                                    <div className="banner-item" key={item.imageUrl}>
                                        <img className="image" src={item.imageUrl} alt={item.typeTitle} />
                                    </div>
                                )
                            })
                        }
                    </Carousel>
                </BannerLeft>
                <BannerRight></BannerRight>
                <BannerControl>
                    <button className="btn left" onClick={e => bannerRef.current.prev()}></button>
                    <button className="btn right" onClick={e => bannerRef.current.next()}></button>
                </BannerControl>
            </div>
        </BannerWrapper>
    )
})
// 传统形式：connect 联系获取redux，不如上面的hook用的爽

// class LwtTopBanner extends PureComponent {
//     componentDidMount() {
//         this.props.getTopBanner()
//     }
//     render() {
//         const topBanners = this.props.topBanners
//         return (
//             <div>
//                 <h2>topbanner</h2>
//             </div>
//         )
//     }
// }

// const mapStateToProps = state => ({
//     topBanners: state.recommend.topBanners
// })

// const mapDispatchToProps = dispatch => ({
//     getTopBanner() {
//         dispatch(getTopBannerAction());
//     }
// })

// export default connect(mapStateToProps, mapDispatchToProps)(LwtTopBanner)